package com.xyz.service.impl;

import com.aliyuncs.AcsResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.ocr.model.v20191230.RecognizeLicensePlateRequest;
import com.aliyuncs.ocr.model.v20191230.RecognizeLicensePlateResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyz.entity.VehicleOwnerInfo;
import com.xyz.entity.ViolationRecord;

import com.xyz.entity.request.PostViolationRecordRequest;
import com.xyz.mapper.ViolationRecordMapper;
import com.xyz.service.IVehicleOwnerInfoService;
import com.xyz.service.IViolationRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 违章信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-04-27
 */
@Service
public class ViolationRecordServiceImpl extends ServiceImpl<ViolationRecordMapper, ViolationRecord> implements IViolationRecordService {
    private final IVehicleOwnerInfoService vehicleOwnerInfoService;
    private final IAcsClient client;

    public ViolationRecordServiceImpl(IVehicleOwnerInfoService vehicleOwnerInfoService) {
        this.vehicleOwnerInfoService = vehicleOwnerInfoService;
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "LTAI5tHc1r8vRCHunUvYQm52",
                "18FUxpqGmpYvSnDIrCnZiLVGXpQ3v6");
        client = new DefaultAcsClient(profile);
    }

    @Override
    public Page<ViolationRecord> listByIdNumber(String idNumber, Integer page, Integer limit) {
        List<VehicleOwnerInfo> plateList = this.vehicleOwnerInfoService.lambdaQuery().select(VehicleOwnerInfo::getPlateNumber).eq(VehicleOwnerInfo::getIdNumber, idNumber).list();
        if (CollectionUtils.isEmpty(plateList)) {
            return new Page<>();
        }
        List<String> collect = plateList.stream().map(VehicleOwnerInfo::getPlateNumber).collect(Collectors.toList());
        return this.lambdaQuery().in(ViolationRecord::getPlateNumber, collect).page(new Page<>(page, limit));
    }

    @Override
    public void postViolationRecord(PostViolationRecordRequest request) {
        ViolationRecord violationRecord = new ViolationRecord();
        BeanUtils.copyProperties(request, violationRecord);
        violationRecord.setPlateNumber(this.getPlateNumber(request.getImage()));
        this.save(violationRecord);
    }

    private <R extends RpcAcsRequest<T>, T extends AcsResponse> T getAcsResponse(R req) throws Exception {
        try {
            return client.getAcsResponse(req);
        } catch (ServerException e) {
            // 服务端异常
            System.out.println(String.format("ServerException: errCode=%s, errMsg=%s", e.getErrCode(), e.getErrMsg()));
            throw e;
        } catch (ClientException e) {
            // 客户端错误
            System.out.println(String.format("ClientException: errCode=%s, errMsg=%s", e.getErrCode(), e.getErrMsg()));
            throw e;
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
            throw e;
        }
    }

    public String getPlateNumber(String imgUrl) {
        RecognizeLicensePlateRequest req = new RecognizeLicensePlateRequest();
        req.setImageURL(imgUrl);
        try {
            RecognizeLicensePlateResponse resp = getAcsResponse(req);
            return resp.getData().getPlates().get(0).getPlateNumber();
        } catch (Exception e) {
            throw new RuntimeException("识别错误");
        }
    }
}
